package com.onlineshop.controller.admin;

import com.onlineshop.dao.ProductDao;
import com.onlineshop.entity.Product;
import com.onlineshop.util.FileUploadUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

@WebServlet("/admin/products/add")
public class AddProductServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/admin/add_product.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求字符编码
        request.setCharacterEncoding("UTF-8");
        // 使用FileUploadUtil解析请求
        Map<String, String> formFields = FileUploadUtil.parseRequest(request);

        // 从formFields中获取参数
        String name = formFields.get("name");
        String priceStr = formFields.get("price");
        String stockStr = formFields.get("stock");
        String description = formFields.get("description");
        String image = formFields.get("image"); // 获取上传的文件名

        // 验证参数
        if (name == null || name.trim().isEmpty() ||
                priceStr == null || priceStr.trim().isEmpty() ||
                stockStr == null || stockStr.trim().isEmpty()) {
            request.setAttribute("error", "必填字段不能为空");
            request.getRequestDispatcher("/admin/add_product.jsp").forward(request, response);
            return;
        }

        try {
            BigDecimal price = new BigDecimal(priceStr);
            int stock = Integer.parseInt(stockStr);

            Product product = new Product(name, price, stock, description, image);
            int productId = productDao.addProduct(product);

            if (productId > 0) {
                response.sendRedirect(request.getContextPath() + "/admin/products?success=添加商品成功");
            } else {
                request.setAttribute("error", "添加商品失败");
                request.getRequestDispatcher("/admin/add_product.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "文件上传失败：" + e.getMessage());
            request.getRequestDispatcher("/admin/add_product.jsp").forward(request, response);
        }
    }
}